//
//  ManualSignViewController.m
//  ZPIOSEducation
//
//  Created by 董伟1 on 17/3/6.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "ManualSignViewController.h"
#import "ManualSignCell.h"

#define SignAlertDefaultTag  1000

@interface ManualSignViewController () <UITableViewDelegate,UITableViewDataSource>
{
    BOOL  changed;
    UIView  *headerView;
    NSMutableArray  *dataArray;
}

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@end

@implementation ManualSignViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"手动签到";
    changed = NO;
    dataArray = [[NSMutableArray  alloc] init];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    
    [self  requestSignList];
    
}

- (void)viewDidLayoutSubviews{
    self.mainTableView.tableHeaderView = [self  createTableHeaderView];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (changed) {
        [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshCourseList" object:nil];
    }
}

- (UIView  *)createTableHeaderView
{
    if (!headerView) {
        headerView = [[[NSBundle mainBundle] loadNibNamed:@"ManualSignHeaderView" owner:self options:nil] lastObject];
        headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
    }
    
    UILabel  *tempLab = (UILabel  *)[headerView  viewWithTag:1000];
    tempLab.text = [NSString  stringWithFormat:@"%@",self.classNameStr];
    
    return headerView;
}

- (void)cellStatusButtonClick:(id)sender
{
    UIButton  *tempBtn = (UIButton  *)sender;
    NSDictionary  *tempDic = [dataArray  objectAtIndex:tempBtn.tag];
    
    UIAlertView  *alertView = [[UIAlertView alloc] initWithTitle:[NSString  stringWithFormat:@"确认给 %@ 签到吗？",[tempDic objectForKey:@"stuName"]] message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.tag = SignAlertDefaultTag + tempBtn.tag;
    [alertView  show];
}

#pragma mark - 网络相关
#pragma mark 手动签到列表
- (void)requestSignList
{
    if (self.scheduleIdStr) {
        [self  showHudithString:@"加载中..."];
        NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[NSString  stringWithFormat:@"%@",self.scheduleIdStr],@"id", nil];
        [[ZPNetworking  sharedZPNetworking] POST:APIPPT@"teacher/getSignListByManual.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
            
        } success:^(id  _Nonnull responseObject) {
            NSLog(@"======%@",responseObject);
            [self  hiddenHud];
            if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
                if ([[responseObject  objectForKey:@"result"] isKindOfClass:[NSArray  class]]) {
                    [dataArray  removeAllObjects];
                    [dataArray  addObjectsFromArray:[responseObject  objectForKey:@"result"]];
                    [self.mainTableView  reloadData];
                }
            }else {
                [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
            }
            
        } failure:^(NSError * _Nonnull error) {
            [self  hiddenHud];
        }];
    }
}

#pragma mark 签到
- (void)sendUpdateSignWithIndex:(NSInteger)index
{
    NSDictionary  *tempDic = [dataArray  objectAtIndex:index];
    [self  showHudithString:@"发送中..."];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:
                               [NSString  stringWithFormat:@"%@",self.scheduleIdStr],@"id",
                               [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"teacherId",
                               [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"stuNumber"]],@"stuNumber",
                               nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIPPT@"teacher/updateSign.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                changed = YES;
                [ZPPromptView  showMessage:@"签到成功"];
                NSMutableDictionary  *newDic = [NSMutableDictionary  dictionaryWithDictionary:tempDic];
                [newDic  setObject:@"1" forKey:@"isSign"];
                [dataArray  replaceObjectAtIndex:index withObject:newDic];
                [self.mainTableView  reloadData];
            }
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray  count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 42.;
}

- (UITableViewCell  *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ManualSignCell";
    ManualSignCell  *cell = (ManualSignCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ManualSignCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.statusBtn  addTarget:self action:@selector(cellStatusButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    NSInteger  row = [indexPath  row];
    NSDictionary  *tempDic = [dataArray  objectAtIndex:row];
    
    cell.statusBtn.tag = row;
    cell.nameLab.text = [NSString  stringWithFormat:@"%ld、%@(%@)",(long)(row + 1),[tempDic objectForKey:@"stuName"],[tempDic objectForKey:@"stuNumber"]];
    NSInteger  isSign = [[tempDic  objectForKey:@"isSign"] integerValue];
    if (isSign == 0) {
        [cell.statusBtn  setTitle:@"签到" forState:UIControlStateNormal];
        [cell.statusBtn  setBackgroundColor:UIColorFromRGB(0x21a4eb)];
        cell.statusBtn.userInteractionEnabled = YES;
    }else {
        [cell.statusBtn  setTitle:@"已签到" forState:UIControlStateNormal];
        [cell.statusBtn  setBackgroundColor:UIColorFromRGB(0x999999)];
        cell.statusBtn.userInteractionEnabled = NO;
    }
    
    return cell;
    
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self  sendUpdateSignWithIndex:alertView.tag - SignAlertDefaultTag];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
